package com.api.gbhg.luoao.utils;

import com.google.common.base.Joiner;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import weaver.conn.RecordSet;
import weaver.conn.RecordSetTrans;
import weaver.general.BaseBean;

import java.util.*;

public class ApperverDao {
    public static final Logger LOGGER = LoggerFactory.getLogger("gbhg");
    //插入数据至授权列表
    public static  boolean insertApperver(Map<String,Object> map){
        RecordSet rs = new RecordSet();
        boolean b = rs.executeUpdate("INSERT INTO uf_dwysbzrywh (bmxfdcs,dwyscwry,ysbzjbr,ysbzhpr) " +
                    "VALUES ('"+map.getOrDefault("dw","")+"'" +
                    ",'"+map.getOrDefault("dwyscwry","")+"'" +
                    ",'"+map.getOrDefault("ysbzjbr","")+"'" +
                    ",'"+map.getOrDefault("ysbzhpr","")+"')"
                );
        return  b;
    }

    //插入数据至角色表
    public static boolean insertRole(Map<String,Object> map){
        String ysbzhpr = new BaseBean().getPropValue("gbhg-zpshouquan", "ysbzhpr");
        String ysbzjbr = new BaseBean().getPropValue("gbhg-zpshouquan", "ysbzjbr");
        String cwry = new BaseBean().getPropValue("gbhg-zpshouquan", "cwry");
        //判断数据是否存在，不存在就插入
        if (getexist(map.get("ysbzhpr").toString(),ysbzhpr) && getexist(map.get("ysbzjbr").toString(),ysbzjbr)&& getexist(map.get("dwyscwry").toString(),cwry)){
            return  true;
        }
        return false;
    }


    //判断是否存在
    public static boolean getexist(String userid,String roleid){
        if("".equals(userid) || userid == ""){
            return true;
        }
        List<String> rsid =  Arrays.asList(userid.split(","));
        if(rsid.size()>0){
            RecordSet rs = new RecordSet();
            RecordSet recordSet = new RecordSet();
            for (int i=0;i<rsid.size();i++){
                String sql="select * from hrmrolemembers " +
                        "where roleid =" + roleid + "  and resourceid =" + rsid.get(i);
                LOGGER.info(String.format("判断角色是否存在>>>>%s",sql));
                recordSet.executeQuery(sql);
                if (!recordSet.next()){
                    rs.executeUpdate("insert into hrmrolemembers(roleid,resourceid,rolelevel,resourcetype,uuid)" +
                                    " values(?,?,?,?,?)",
                            roleid, rsid.get(i),"2","1", UUID.randomUUID().toString()
                    );
                }
            }
        }
        return true;
    }


    //更新数据至矩阵表
    public static boolean UpdateMatrix(Map<String,Object> map){
        //先更新分部自定义字段表
        String[] dws = getfilter(map.get("dw").toString());
        RecordSet rs = new RecordSet();
        String sql="select * from HrmSubcompanyDefined where subcomid="+map.get("dw");
        LOGGER.info(sql);
        rs.executeQuery(sql);
        while (rs.next()){
            boolean b = rs.executeUpdate("update HrmSubcompanyDefined set ysbzhpr = ?, ysbzjbr = ? where subcomid = ?",
                    dws[0], dws[1], map.getOrDefault("dw", "")
            );
            return b;
        }
        //不存在 插入
        String insertSql="insert into HrmSubcompanyDefined (subcomid, ysbzjbr, ysbzhpr, dwyscwry) values (?,?,?,?)";
        LOGGER.info(insertSql);
        boolean f1 = rs.executeUpdate(insertSql,map.get("dw"),map.get("ysbzjbr"),map.get("ysbzhpr"),map.get("dwyscwry"));
        //再更新矩阵表
        RecordSet rs2 = new RecordSet();
        String updateSql = "update Matrixtable_1 set ysbzhpr=?,ysbzjbr=?,dwyscwry=? where id=?";
        LOGGER.info(updateSql);
        boolean f2 = rs2.execute(updateSql);
        if(f1 && f2){
            return  true;
        }else{
            return  false;
        }
    }


    //过滤授权列表中的数据
    public static  String[] getfilter(String dw){
        RecordSet rs = new RecordSet();
        rs.executeQuery("select ysbzhpr,ysbzjbr from uf_dwysbzrywh where bmxfdcs = "+dw);
        List ysbzhpr = new ArrayList();
        List ysbzjbr = new ArrayList();

        while (rs.next()){
            ysbzhpr.add(rs.getStringNoTrim("ysbzhpr"));
            ysbzjbr.add(rs.getStringNoTrim("ysbzjbr"));
        }
        String[]  personnel = {Joiner.on(",").join((Iterable<?>) ysbzhpr),Joiner.on(",").join((Iterable<?>) ysbzjbr)};
        return personnel;
    }


    //更新授权列表
    public static  boolean UpdetaApperverId(Map<String,Object> map){
        RecordSet rs = new RecordSet();
        boolean b = rs.executeUpdate("UPDATE uf_dwysbzrywh set dwyscwry=?,ysbzjbr =?, ysbzhpr =? where bmxfdcs =? ",
                    map.getOrDefault("dwyscwry",""),
                    map.getOrDefault("ysbzjbr",""),
                    map.getOrDefault("ysbzhpr",""),
                    map.getOrDefault("dw","")
                );
        return  b;
    }


    //根据id删除授权列表数据
    public static boolean DeleteApperverId(Map<String,Object> map){
        RecordSet rs = new RecordSet();
        boolean b = rs.executeUpdate("delete from uf_dwysbzrywh where bmxfdcs =?",map.getOrDefault("dw",""));
        return  b;
    }


    //更新角色表
    public static boolean UpdateRole(RecordSetTrans rst, Map<String,Object> map){
        //先查找上个版本的数据

        return  false;
    }


    /**
     * 删除对应授权角色中的人员
     * @param roleid
     * @param resoureid
     * @param str 用于盘点操作哪个角色
     * @return
     */
    public static  boolean DeleteRole(String roleid,String resoureid,String str){
        //LOGGER.info("roleid="+roleid+",resoureid="+resoureid+",str="+str);
        boolean b = false;
        List<String> rsid;
        RecordSetTrans rst = new RecordSetTrans();
        RecordSet rs = new RecordSet();
        if(!"".equals(resoureid) && resoureid != ""){
            try {
                String updateSql = "delete from hrmrolemembers where " + " roleid in('"+roleid+"')  and resourceid in("+resoureid+") ";
                LOGGER.info(updateSql);
                b = rst.executeUpdate(updateSql);
            }catch (Exception e){
                e.printStackTrace();
                rst.rollback();
            }
//            rsid = Arrays.asList(resoureid.split(","));
//            //删除前要先判断 该人员在其他的单位有没有被授权
//            ///b = rst.executeUpdate("delete from hrmrolemembers where " + " roleid in('"+roleid+"')  and resourceid in("+resoureid+") ");
//            if("ysbzhpr".equals(str)){
//                //校验删除收入预算编制人角色
//                LOGGER.info("校验删除收入预算编制人角色开始");
//                for(int i=0;i<rsid.size();i++){
//                    String sql = "select subcomid from HrmSubcompanyDefined where  ysbzhpr like '%"+rsid.get(i)+"%'";
//                    LOGGER.info(sql);
//                    rs.execute(sql);
//                    rs.next();
//                    if(rs.getCounts()>1){
//                        continue;
//                    }else{
//                        try {
//                            String updateSql = "delete from hrmrolemembers where " + " roleid in('"+roleid+"')  and resourceid in("+rsid.get(i)+") ";
//                            LOGGER.info(updateSql);
//                            b = rst.executeUpdate(updateSql);
//                        }catch (Exception e){
//                            e.printStackTrace();
//                            rst.rollback();
//                            break;
//                        }
//                    }
//                }
//                LOGGER.info("校验删除收入预算编制人角色结束");
//            }else if("ysbzjbr".equals(str)){
//                //校验删除支出预算编制人角色
//                LOGGER.info("校验删除支出预算编制人角色开始");
//                for(int i=0;i<rsid.size();i++){
//                    String sql = "select subcomid from HrmSubcompanyDefined where  ysbzjbr like '%"+rsid.get(i)+"%'";
//                    rs.execute(sql);
//                    rs.next();
//                    if(rs.getCounts()>1){
//                        continue;
//                    }else{
//                        try {
//                            String updateSql = "delete from hrmrolemembers where " + " roleid in('"+roleid+"')  and resourceid in("+rsid.get(i)+") ";
//                            LOGGER.info(updateSql);
//                            b = rst.executeUpdate(updateSql);
//                        }catch (Exception e){
//                            e.printStackTrace();
//                        }
//                    }
//                }
//                LOGGER.info("校验删除支出预算编制人角色结束");
//            }else{
//
//            }
        }else{
            LOGGER.info("不需要操作删除角色表");
            return true;
        }
        return  b;
    }

    //更新分部矩阵表中的相关字段为空
    public static  boolean UpdateMatrix(String dw){
        boolean b = false;
        RecordSetTrans rst = new RecordSetTrans();
        try {
            String updateSql = "update Matrixtable_1 set ysbzhpr='',ysbzjbr='',dwyscwry='' where id="+dw;
            LOGGER.info("更新分部矩阵表中的相关字段为空>>"+updateSql);
            b = rst.executeUpdate(updateSql);
        } catch (Exception e) {
            e.printStackTrace();
            rst.rollback();
        }
        return  b;
    }


}
